/*Confidential and Proprietary, Subject to the Non-Disclosure Agreement,
 Version 1.0, between the Development Gateway Foundation, Inc and the
 Recipient Copyright 2001-2004 Development Gateway Foundation, Inc.

 Local Projects Database
 */
package ro.gateway.aida.db;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.TreeSet;

import javax.servlet.ServletContext;

/**
 * @author Mihai Postelnicu e-mail: mihai@ro-gateway.org
 */
public class DBConnectorProperties {
	private Properties p;

	private ServletContext sc;

	private List connectors;

	private String current=null;

	/**
	 *  
	 */
	public DBConnectorProperties(ServletContext sc) {
		p = new Properties();
		this.sc = sc;
	}

	private void load() throws IOException {
	    try {
		p.load(sc.getResourceAsStream(fileName));
		current = getCurrentConnectorName();
	    } catch (Exception e) {
	        
	    }
	}

	private String getCurrentConnectorName() throws IOException {
		if (p == null)
			load();
		return p.getProperty("current");
	}

	public void saveConnectors() throws IOException {
		Iterator i = connectors.iterator();
		p = new Properties();
		
		if (current == null && connectors.size() != 0)
			p.setProperty("current", ((DBConnector) connectors.get(0))
					.getName());
		else
			if(current!=null) p.setProperty("current", current);
		while (i.hasNext()) {
			DBConnector element = (DBConnector) i.next();
			if (element instanceof PostgresDBConnector) {
				p.setProperty(element.getName() + "." + "type", "postgres");
				p.setProperty(element.getName() + "." + "dbname",
						((PostgresDBConnector) element).getDbName());
			}

			if (element instanceof OracleDBConnector) {
				p.setProperty(element.getName() + "." + "type", "oracle");
				p.setProperty(element.getName() + "." + "tablespace",
						((OracleDBConnector) element).getTablespace());
			}
			p.setProperty(element.getName() + "." + "host", element.getHost());
			p.setProperty(element.getName() + "." + "user", element.getUser());
			p.setProperty(element.getName() + "." + "password", element
					.getPassword());

		}
	
		
 		FileOutputStream fos=new FileOutputStream(sc.getRealPath(fileName));
		p.store(fos, "Local Projects Database - db configurator file. Please do NOT delete!");
		fos.close();
	}

	/**
	 * @return a list of DBConnector objects that can be used to create database
	 *         connections
	 * @throws IOException
	 */
	public void loadConnectors() throws IOException, NumberFormatException {
			load();
		ArrayList ret = new ArrayList();
		//acquire connectors
		TreeSet connNames = new TreeSet();
		Enumeration en = p.propertyNames();
		while (en.hasMoreElements()) {
			String element = (String) en.nextElement();
			if (element.indexOf('.') == -1)
				continue;
			connNames.add(element.substring(0, element.indexOf('.')));
		}
		Iterator i = connNames.iterator();
		while (i.hasNext()) {
			DBConnector cbean = null;
			String conn = (String) i.next();
			String type = p.getProperty(conn + "." + "type");
			String password = p.getProperty(conn + "." + "password");
			String host = p.getProperty(conn + "." + "host");
			String port = p.getProperty(conn + "." + "port");
			String user = p.getProperty(conn + "." + "user");
			if (type == null || password == null || host == null)
				continue;

			if (type.equals("postgres")) {
				String db = p.getProperty(conn+"."+"dbname");
				if (db == null)
					continue;
				cbean = new PostgresDBConnector(db);
			}

			if (type.equals("oracle")) {
				String db = p.getProperty(conn+"."+"tablespace");
				if (db == null)
					continue;
				cbean = new OracleDBConnector(db);
			}

			if (cbean == null)
				continue;

			cbean.setName(conn);
			cbean.setHost(host);
			cbean.setUser(user);
			cbean.setPassword(password);
			if (port != null)
				cbean.setPort(Integer.parseInt(port));
			ret.add(cbean);
		}
		connectors = ret;
		
		if(connectors.size()!=0 && getConnector(current)==null) {
		    current=((DBConnector)connectors.get(0)).getName();
		    saveConnectors();
		}
		
		if (current==null) current="[unset]";
	}

	public DBConnector getConnector(String name) throws IOException {
		if (connectors == null)
			loadConnectors();
		Iterator i = connectors.iterator();
		while (i.hasNext()) {
			DBConnector element = (DBConnector) i.next();
			if (element.getName().equals(name))
				return element;
		}
		return null;
	}

	public static final String fileName = "/WEB-INF/database.properties";

	/**
	 * @return Returns the fileName.
	 */
	public static String getFileName() {
		return fileName;
	}

	/**
	 * @return Returns the connectors.
	 */
	public List getConnectors() {
		return connectors;
	}

	/**
	 * @param connectors
	 *            The connectors to set.
	 */
	public void setConnectors(List connectors) {
		this.connectors = connectors;
	}

	/**
	 * @return Returns the current.
	 */
	public String getCurrent() {
		return current;
	}

	/**
	 * @param current
	 *            The current to set.
	 */
	public void setCurrent(String current) {
		this.current = current;
	}
}